﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeProjectsModel;

namespace WeProjects.Controllers
{
    public class ResourceController : Controller
    {
        //
        // GET: /Resource/
        private static ProjectsDBEntities db;
        public ResourceController()
        {
            if (db == null)
            {
                db= new ProjectsDBEntities();
            }
        }

        public ActionResult Index()
        {            
            return View(db.Resources.OrderBy(r=>r.Title));
        }
        [HttpPost]
        [Authorize(Roles = "sysadmin")]
        public string Upload(HttpPostedFileBase fileData)
        {
            string returnMsg = "";
            if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(fileData.FileName);
                // store the file inside ~/App_Data/uploads folder
                var path = Path.Combine(Server.MapPath("~/App_Data/Resources/"));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (!System.IO.File.Exists(Path.Combine(path, fileName)))//If this is a new file
                {
                    fileData.SaveAs(Path.Combine(path, fileName));
                    db.Resources.Add(new Resource() { FileName = fileName, Description = fileName, Size = (int)(fileData.ContentLength / 1024), Title = fileName, UploadDateTime = DateTime.Now });
                    db.SaveChanges();
                    returnMsg = "OK";
                }
                else
                {
                    returnMsg = "Another file with the same name already exist. Please change the file name and then reupload.";
                }
            }
            else
            {
                returnMsg = "This file seems to be 0 in size.";
            }
            return returnMsg;
        }
        [HttpPost]
        [Authorize(Roles = "sysadmin")]
        public string ChangeFile(HttpPostedFileBase fileData,int recourceID )
        {
            string returnMsg = "";
            var resource = db.Resources.Find(recourceID);
            if(resource==null)
            {
                returnMsg="资源不存在！";                
            }
            else if (fileData != null && fileData.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(fileData.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/Resources/"));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if(resource.FileName.ToLower()!=fileName.ToLower())//Delete the old file, if both have the same file name.
                {
                    System.IO.File.Delete(Path.Combine(path, fileName));
                }

                if (!System.IO.File.Exists(Path.Combine(path, fileName)))//Make sure there is no file with the same name.
                {
                    fileData.SaveAs(Path.Combine(path, fileName));
                    resource.FileName = fileName;
                    resource.Size = (int)(fileData.ContentLength / 1024);
                    db.Entry(resource).State= EntityState.Modified;
                    //db.Resources.Add(new Resource() { FileName = fileName, Description = fileName, Size = (int)(fileData.ContentLength / 1024), Title = fileName, UploadDateTime = DateTime.Now });
                    db.SaveChanges();
                    returnMsg = "OK";
                }
                else
                {
                    returnMsg = "Another file with the same name already exist. Please change the file name and then reupload.";
                }
            }
            else
            {
                returnMsg = "This file seems to be 0 in size.";
            }
            return returnMsg;
        }
        public FileResult Download(int id) //Resource ID.
        {
            var resource = db.Resources.Find(id);
            if(resource==null)
            {
               //return HttpNotFound();
            }
            var path = Path.Combine(Server.MapPath("~/App_Data/Resources/"));
            string fullName = Path.Combine(path,resource.FileName);//Title is filename
            if (Directory.Exists(path) && System.IO.File.Exists(fullName))
            {
                byte[] fileBytes = Helps.Utility.GetFile(fullName);
                return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, resource.FileName);
            }
            else
            {
                return null;// HttpNotFound("File requested doesn't exist. Contact administrator please.");
            }
        }
        //
        // GET: /Resource/Details/5

        public ActionResult Details(int id)
        {
            Resource resource = db.Resources.Find(id);
            if(resource==null)
            {
                return HttpNotFound();
            }
            return View(resource);
        }

        //
        // GET: /Resource/Create
                
        [Authorize(Roles = "sysadmin")]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Resource/Create

        [HttpPost]
        [Authorize(Roles = "sysadmin")]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Resource/Edit/5        
        [Authorize(Roles = "sysadmin")]
        public ActionResult Edit(int id)
        {
            Resource resource=db.Resources.Find(id);
            return View(resource);
        }

        //
        // POST: /Resource/Edit/5

        [HttpPost]        
        [Authorize(Roles = "sysadmin")]
        public ActionResult Edit(Resource resource)
        {
            if (ModelState.IsValid)
            {
                Resource res = db.Resources.Find(resource.ID);
                if (res == null)
                {
                    return HttpNotFound();
                }
                res.Title = resource.Title;
                res.Description = resource.Description;
                res.UploadDateTime = DateTime.Now;
                db.Entry(res).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Details", new { id = res.ID });
            }
            return View(resource);
        }
        
        //
        // GET: /Resource/Delete/5
        
        [Authorize(Roles = "sysadmin")]
        public ActionResult Delete(int id)
        {
            Resource resource=db.Resources.Find(id);
            if(resource==null)
            {
                return HttpNotFound();
            }
            return View(resource);
        }

        //
        // POST: /Resource/Delete/5

        [HttpPost, ActionName("Delete")]
        [Authorize(Roles = "sysadmin")]
        public ActionResult DeleteConfirmed(int id)
        {
            //1.Make sure the resource exists.
            Resource resource = db.Resources.Find(id);
            if (resource == null)
            {
                return HttpNotFound();
            }
            //2.Delete file if exists.
            var path = Path.Combine(Server.MapPath("~/App_Data/Resources/"));
            string fullName = Path.Combine(path,resource.FileName);//Title is filename
            if (Directory.Exists(path) && System.IO.File.Exists(fullName))
            {
                System.IO.File.Delete(fullName);
            }
            //3.Delete database entity
            db.Resources.Remove(resource);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}
